import React, { useCallback } from 'react';

import Loader from 'components/Loader';
import Text from 'components/Text';
import { TEXT_TAG, TEXT_VIEW } from 'components/Text/Text.types';
import { classnames } from 'utils';

import classes from './Button.module.scss';

export type ButtonProps = React.ButtonHTMLAttributes<HTMLButtonElement> & {
    /** Состояние загрузки */
    loading?: boolean;
    /** Текст кнопки */
    children: React.ReactNode;
};

const cnButton = classnames(classes, 'button');

const Button: React.FC<ButtonProps> = ({ loading, children, className, disabled, onClick, ...props }) => {
    const handleOnClick = useCallback((e: React.MouseEvent<HTMLButtonElement>) => {
        e.stopPropagation();
        onClick?.(e);
    }, []);
    return (
        <button
            {...props}
            className={cnButton({ loading, disabled }) + ` ${className}`}
            disabled={disabled || loading}
            onClick={handleOnClick}
        >
            {loading && <Loader size="s" className={cnButton('loader', { disabled })} />}
            <Text tag={TEXT_TAG.span} view={TEXT_VIEW.button}>
                {children}
            </Text>
        </button>
    );
};

export default Button;
